/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;

/**
 * 
 * @author max.zheng
 * @create 2015-8-27下午10:32:33
 * @since 1.0
 * @see
 */
public class UDPReceiver {
	public static void main(String[] args) {

		try {
			InetAddress address = InetAddress.getLocalHost();
			System.out.println("服务端hostIp="+address.getHostAddress());
			int port = 8999;

			// 创建DatagramSocket对象
			DatagramSocket socket = new DatagramSocket(port, address);

			byte[] buf = new byte[1024]; // 定义byte数组
			DatagramPacket packet = new DatagramPacket(buf, buf.length); // 创建DatagramPacket对象

			socket.receive(packet); // 通过套接字接收数据

			String getMsg = new String(buf, 0, packet.getLength());
			System.out.println("客户端发送的数据为：" + getMsg);
			
			Thread.sleep(30000);
			// 从服务器返回给客户端数据
			InetAddress clientAddress = packet.getAddress(); // 获得客户端的IP地址
			System.out.println(clientAddress.getHostAddress());
			int clientPort = packet.getPort(); // 获得客户端的端口号
			SocketAddress sendAddress = packet.getSocketAddress();
			String feedback = "Received";
			byte[] backbuf = feedback.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(backbuf,
					backbuf.length, sendAddress); // 封装返回给客户端的数据
			socket.send(sendPacket); // 通过套接字反馈服务器数据

			socket.close(); // 关闭套接字

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
